package com.example.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Spring Context 工具类
 * ApplicationContextAware 接口的实现类，setApplicationContext 方法会在 Spring 容器初始化时自动调用，
 * 用于将 Spring 容器中的 ApplicationContext 对象注入到当前类中，
 * 从而可以在当前类中获取 Spring 容器中的 Bean。
 */
public class SpringContextUtils implements ApplicationContextAware {

    public static ApplicationContext applicationContext;

    /**
     * 获取 Spring 容器中的 Bean
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }
}
